package nio.one;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/*
    分散和聚集操作数据
 */
public class ChannelTest04 {
    public static void main(String[] args) {
        File originFile = new File("E:\\mycode\\io\\src\\nio\\one\\test.txt");
        File targetFile = new File("E:\\mycode\\io\\src\\nio\\one\\test2.txt");
        try (
                FileInputStream fis = new FileInputStream(originFile);
                FileOutputStream fos = new FileOutputStream(targetFile);
                //获取通道
                FileChannel fisChannel = fis.getChannel();
                FileChannel fosChannel = fos.getChannel();
        ) {
            //定义多个缓冲区
            ByteBuffer[] buffers = new ByteBuffer[]{ByteBuffer.allocate(3),ByteBuffer.allocate(10)};
            //从通道中读取数据分散到多个缓冲区
            fisChannel.read(buffers);
            for(ByteBuffer buffer:buffers){
                buffer.flip();
                System.out.println(new String(buffer.array(),0,buffer.remaining()));
            }
            //将多个缓冲区的数据写入到文件中
            fosChannel.write(buffers);
        } catch (Exception e) {
        }
    }
}
